/*
 * =====================================================================================
 *
 *       Filename:  dispatcherThreadPoll.cpp
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  08/03/2012 08:45:26 PM
 *       Revision:  none
 *       Compiler:  gcc/g++
 *
 *         Author:  wangtengchao , wangtengchao AT gmail.com
 *   Organization:
 *
 * =====================================================================================
 */


#include "dispatcherThread.h"
#include "dispatcherThreadPool.h"

    #include<cstdio>

using namespace inm::net;
DispatcherThreadPool::DispatcherThreadPool(int threadNum):
    threadNum_(threadNum),
    dispatcherThreads_(threadNum), //initialize the threadpool size by threadNum
    isStarted(false),
    next_(0)
{
    DispatcherThread* p = NULL;
    for(int i=0;i<threadNum_;i++)
    {
        p = new DispatcherThread(i);
        dispatcherThreads_[i] = p;
    }

}

DispatcherThreadPool::~DispatcherThreadPool()
{
    assert(threadNum_ = dispatcherThreads_.size());
    for(int i=0;i<threadNum_ && dispatcherThreads_[i]!=NULL;i++)
        delete dispatcherThreads_[i];
}

Dispatcher* DispatcherThreadPool::getNextDispatcher()
{//round-robin  --only called by Acceptor Reactor. don't need mutex
 //next_ record the next dispatcher's index
    //inm::concurrency::MutexLockGuard lock(mutex_);
    assert(next_ <= threadNum_);
    Dispatcher* p = dispatcherThreads_[next_++]->getDispatcher();
    if(next_ == threadNum_)
        next_ = 0;
#ifdef NET_BUG
    printf("getNextDispatcher: %d \n",next_-1);
#endif
    return p;
}
void DispatcherThreadPool::start()
{
    isStarted = true;
    assert(threadNum_ == dispatcherThreads_.size());
    for(int i=0;i<threadNum_;i++)
        dispatcherThreads_[i]->start();

}
void DispatcherThreadPool::quit()
{
    size_t s = dispatcherThreads_.size();
    for(size_t i = 0;i<s;i++)
        dispatcherThreads_[i]->quit();
}
